<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"/>
        <span>筛选搜索</span>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="queryInfo" size="small" label-width="140px">
          <el-form-item label="人脉圈标题：">
            <el-input style="width: 300px" v-model="queryInfo.query.productName" placeholder="请输入人脉圈标题"></el-input>
          </el-form-item>
          <el-form-item label="人脉圈类型：">
            <el-input style="width: 300px" v-model="queryInfo.query.productSn" placeholder="请选择人脉圈类型"></el-input>
          </el-form-item>
          <el-button
            style="float: right"
            type="primary"
            size="medium"
            icon="el-icon-search"
            @click="getDataList()"
          >
            搜索
          </el-button>
          <el-button
            style="float: right;margin-right: 15px"
            size="medium"
            @click="handleResetSearch()"
          >
            重置
          </el-button>
        </el-form>

      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"/>
      <span>人脉圈列表</span>
      <el-button
        class="btn-add"
        size="medium"
        type="primary"
        style="float: right;margin-bottom: 15px"
        icon="el-icon-plus"
        @click="showDialog(0, 'show')"
      >
        添加
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="tableList"
        v-loading="listLoading"
        :data="datalist"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" width="60" align="center"/>
        <el-table-column label="标题" align="center">
          <template slot-scope="scope">测试人脉圈</template>
        </el-table-column>
        <el-table-column label="类型" width="" align="center">
          <template slot-scope="scope">{{ scope.row.nickName }}同事</template>
        </el-table-column>
        <el-table-column label="话题" align="center">
          <template slot-scope="scope">{{ scope.row.profession }}工作</template>
        </el-table-column>
        <el-table-column label="人数" align="center">
          <template slot-scope="scope"><p>{{ scope.row.name }}100</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <p>
              <el-button
                size="mini"
                type="warning"
                @click="showDialog(scope.row.id, 'edit')"> 管理
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="removeDataById(scope.row.id)"> 删除
              </el-button>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="queryInfo.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="queryInfo.pageNum"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="dialogClosed">
      <!-- 内容主体 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :disabled="type === 'show'"
        label-width="100px"
      >
        <el-row type="flex" justify="center" align="">
          <el-col :span="20">
            <el-form-item label="标题" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入人脉圈标题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="">
          <el-col :span="20">
            <el-form-item label="类型" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入人脉圈类型" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="">
          <el-col :span="20">
            <el-form-item label="话题" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入人脉圈话题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" align="center">
        <el-button type="primary" @click="submitForm"> 确定</el-button>
        <el-button @click="dialogVisible = false"> 取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'GeneralPage',
  data() {
    return {
      apis: {
        list: {
          method: 'get',
          // url: `${constants.remoteService ? 'api/' : ''}parameter/binTable/get/page`,
          url: '/vue-admin-template/table/list'
        },
        update: {
          method: 'post',
          url: '/vue-admin-template/table/list'
        },
        detail: {
          method: 'post',
          url: '/vue-admin-template/table/list'
        },
        create: {
          method: 'post',
          url: '/vue-admin-template/table/list'
        },
        delete: {
          method: 'post',
          url: '/vue-admin-template/table/list'
        }
      },
      type: '',
      // 获取用户列表查询参数对象
      queryInfo: {
        query: {},
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5
      },
      datalist: [],
      listLoading: false,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新建人脉圈',
      forms: [
        {
          key: 'title',
          title: '标题',
          type: 'input'
        },
        {
          key: 'nickName',
          title: '昵称',
          type: 'input'
        },
        {
          key: 'pageviews',
          title: 'pageviews',
          type: 'input'
        }
      ],
      // 用户添加表单验证规则
      formRules: {
        nickName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {
            min: 2,
            max: 10,
            message: '用户名的长度在2～10个字',
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {
            min: 6,
            max: 18,
            message: '用户密码的长度在6～18个字',
            trigger: 'blur'
          }
        ],
        title: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          // { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          // { validator: checkMobile, trigger: 'blur' }
        ]
      },
      pictureAction: 'https://jsonplaceholder.typicode.com/posts/',
      picturefileList: [],
      // 提交表单
      formData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // getList(params) {
    //   console.log('getList-API', params)
    //   return request({
    //     url: '/vue-admin-template/table/list',
    //     method: 'get',
    //     params
    //   })
    // },
    getDataList() {
      this.listLoading = true
      // this.getList(this.queryInfo)
      const params = this.queryInfo
      request({
        url: this.apis.list.url,
        method: this.apis.list.method,
        params
      }).then(response => {
        this.datalist = response.data.items
        console.log(response.data)
        // this.total = res.data.total
        this.listLoading = false
      })
    },
    handleResetSearch() {
      this.queryInfo['query'] = {}
    },
    submitForm() {
      console.log('Type', this.type)
      if (this.type === 'add') {
        this.addData()
      } else {
        this.editData()
      }
    },
    addData() {
      // 提交请求前，表单预验证
      this.$refs.formRef.validate(async valid => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return
        const params = this.formData
        request({
          url: this.apis.create.url,
          method: this.apis.create.method,
          params
        }).then(response => {
          // if (res.meta.status !== 201) {
          //   this.$message.error('添加用户失败！')
          // }
          // this.$message.success('添加用户成功！')
          // 隐藏添加用户对话框
          this.dialogVisible = false
          this.getDataList()
        })
      })
    },
    // 显示对话框
    showDialog(id, str) {
      if (str === "edit") {
        this.dialogTitle = "人脉圈管理"
        const params = id
        request({
          url: this.apis.detail.url,
          method: this.apis.detail.method,
          params
        }).then(response => {
          // if (res.meta.status !== 200) {
          //   return this.$message.error('查询用户信息失败！')
          // }
          this.type = str
          this.formData = response.data
          this.dialogVisible = true
        })
      } else if (str === "add") {
        this.dialogTitle = "新建人脉圈"
      }
      this.dialogVisible = true
    },
    // 修改用户信息
    editData() {
      // 提交请求前，表单预验证
      this.$refs.formRef.validate(async valid => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return
        const params = this.formData
        request({
          url: this.apis.update.url,
          method: this.apis.update.method,
          params
        }).then(response => {
          // if (res.meta.status !== 200) {
          //   this.$message.error('更新用户信息失败！')
          // }
          this.$message.success('更新用户信息成功！')
          // 隐藏添加用户对话框
          this.dialogVisible = false
          this.formData = []
          this.getDataList()
        })
      })
    },
    // 删除
    async removeDataById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const params = id
      request({
        url: this.apis.delete.url,
        method: this.apis.delete.method,
        params
      }).then(response => {
        // if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
        this.$message.success('删除用户成功！')
        this.getDataList()
      })
    },
    handleStatusChange(switchItem, row) {
      const params = new URLSearchParams()
      params.append(switchItem.key, switchItem.key)
      params.append('changeItem', row)
      request({
        url: switchItem.url,
        method: switchItem.method,
        params
      }).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getDataList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageNum = newSize
      this.getDataList()
    },
    // 监听 添加用户对话框的关闭事件
    dialogClosed() {
      this.$refs.formRef.resetFields()
      this.dialogTitle = "新建人脉圈"
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    pictureBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      let isAccept = new RegExp('image/*').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件')
      }
      return isRightSize && isAccept
    },
  }
}
</script>

<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
}
</style>
